$(document).ready(function () {
    dataSourceTests = new kendo.data.DataSource({
        transport: {
            read: {
                url: appBosch.urlTests,
                dataType: "json"
            }
        },
        batch: true,
        schema: {
            model: {
                id: "value",
                fields: {
                    text : { type: "string", editable: false },
                    room : { type: "string", editable: false },
                    capacity : { type: "number", editable: false },
                    start: { type: "date", editable: false }
                }
            }
        }
    });

    $("#gridDisponibles").kendoGrid({
        toolbar: [
            {
                name: "pdf",
                text: "Exportar a PDF"
            },
            {
                name: "excel",
                text: "Exportar a Excel"
            }
        ],
        excel: {
            allPages: true,
            fileName: "Cursos disponibles.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Cursos disponibles.pdf"
        },
        scrollable: true,
        filterable: true,
        selectable: true,
        navigatable: true,
        resizable: true,
        columnMenu: true,
        dataSource: dataSourceTests,
        columns: [
            {field: 'text', title: 'Curso'},
            { field: 'room', title: 'Sala' },
            { field: 'capacity', title: 'Lugares disponibles' },
            { field: 'start', title: 'Fecha', template: '<span title="#=kendo.toString(new Date(start), "F") #" >#=kendo.toString(new Date(start), "d") #</span>' },
            {
                command: [
                    {
                        name: "inscribir",
                        text: "Registrame",
                        click: registerUser
                    }
                ]
            }
        ]
    });

    dataSourceMyTest = new kendo.data.DataSource({
        transport: {
            read: {
                url: appBosch.crud.read,
                dataType: "json"
            }
        },
        batch: true,
        schema: {
            model: {
                id: "value",
                fields: {
                    text : { type: "string", editable: false },
                    room : { type: "string", editable: false },
                    start: { type: "date", editable: false }
                }
            }
        }
    });

    $("#gridInscritos").kendoGrid({
        toolbar: [
            {
                name: "pdf",
                text: "Exportar a PDF"
            },
            {
                name: "excel",
                text: "Exportar a Excel"
            }
        ],
        excel: {
            allPages: true,
            fileName: "Mis cursos.xlsx",
            filterable: true
        },
        pdf: {
            allPages: true,
            fileName: "Mis cursos.pdf"
        },
        scrollable: true,
        filterable: true,
        selectable: true,
        navigatable: true,
        resizable: true,
        columnMenu: true,
        dataSource: dataSourceMyTest,
        columns: [
            {field: 'text', title: 'Curso'},
            { field: 'room', title: 'Sala' },
            { field: 'start', title: 'Fecha', template: '<span title="#=kendo.toString(new Date(start), "F") #" >#=kendo.toString(new Date(start), "d") #</span>' },
            {command: [{name: "baja", text: "Darme de baja", click: unregisterUser}]}
        ]
    });
});

function registerUser(e) {
    $(e.currentTarget).off('click');
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var id = dataItem.id;
    var capacity = dataItem.capacity;

    if( capacity > 0 ) {
        var model = [{value: id}];

        $.get(appBosch.crud.create, {models: kendo.stringify(model)}, function (resp) {
            dataSourceMyTest.read();
            dataSourceTests.read();
            windowTaxi(resp.schedule_id);
        });
    } else {
        alert("Lo sentimos, el curso esta saturado")
    }
}

function unregisterUser(e) {
    e.preventDefault();
    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    var id = dataItem.id;

    $.get(appBosch.crud.destroy, {id: id}, function () {
        dataSourceMyTest.read();
        dataSourceTests.read();
    });
}

function windowTaxi(schedule_id) {
    var contentTemp = $("#windowTemplate").html();
    var temp = kendo.template(contentTemp);
    var jqDialog = $('<div id="kWindow"></div>');
    var kDialog;
    jqDialog.html(temp({}));
    kDialog = jqDialog.kendoWindow({
        title: "Servicio de Taxi",
        width: 700,
        open: function () {
            jqDialog.on('change', '[name=reqTaxi]', function () {
                if ($('[name=reqTaxi]:checked').val() == '1') {
                    $('fieldset').removeAttr('disabled');
                } else {
                    $('fieldset').attr('disabled', 'true');
                }
            });
            $('#saveRequest').on('click', function () {
                if ($('[name=reqTaxi]:checked').val() == '1') {
                    if (validate($('#taxiForm'))) {
                        $.post(
                            appBosch.urlTaxi + '/' + schedule_id,
                            {
                                req: $('[name=reqTaxi]:checked').val(),
                                street: $('#street').val(),
                                number: $('#number').val(),
                                colony: $('#colonia').val(),
                                between_streets: $('#btwStreets').val()
                            },
                            function (resp) {
                                if (resp !== 'false') {
                                    kDialog.close();
                                }
                            }
                        );
                    }
                } else {
                    kDialog.close();
                }
            });
        },
        deactivate: function () {
            kDialog.destroy();
        }
    }).data("kendoWindow").open().center();
}

function validate(jqForm) {
    var resp = true;
    var jqToValidate = jqForm.find('.required');
    jqToValidate.removeClass('has-error');
    for (i = 0; i < jqToValidate.length; i++) {
        if ($(jqToValidate[i]).val() === "") {
            $(jqToValidate[i]).closest('.form-group').addClass('has-error');
            resp = false;
        }
    }
    return resp;
}